/*
 * @Author: jiu yin
 * @Date: 2024-05-07 11:48:32
 * @LastEditTime: 2024-06-19 17:58:42
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\view\scene_studio\component\SceneList.tsx
 * jiu
 */
import { useEffect, useState, useRef } from "react";
import {
	CaretRightOutlined,
	PoweroffOutlined,
	RetweetOutlined,
	SyncOutlined,
	WomanOutlined,
	ManOutlined,
	UserOutlined,
	DashboardOutlined,
	DeleteOutlined,
} from "@ant-design/icons";
import { Button, Image, message, Tabs, Tag, Pagination, Popconfirm, Badge } from "antd";
import "./index.scss";
import { list_studio_program, play_program_switch, del_studio_program } from "@/api/home";
import Add_edit from "./add_edit";
import { socket, addSocketNotify, removeSocketNotify } from "@/utils/webSocket";
import { useRoute } from "@/hooks";
import { getWsStatus, setWsStatus } from "@/utils/sessionStorage";

export default function SceneList() {
	const { push } = useRoute();

	let [list_data, set_list_data] = useState<any>([]);
	let [is_list_data, set_is_list_data] = useState(false);
	let [params, set_params] = useState({ page: 1, total: 0, status: 0 });
	useEffect(() => {
		list_studio_program({ page: params.page, limit: 10, status: params.status }).then((res: any) => {
			set_list_data(res.data.data);
			set_params({ ...params, total: res.data.total, page: 1 });
		});
	}, [is_list_data, params.page, params.status]);

	const item_status = (status: number) => {
		switch (status) {
			case 1:
				return (
					<Tag color="#5864FF" className="ml-10px">
						待运行
					</Tag>
				);
			case 2:
				return (
					<Tag color="#21AB68" className="ml-10px">
						运行中
					</Tag>
				);
			case 3:
				return (
					<Tag color="#BABBC6" className="ml-10px">
						已结束
					</Tag>
				);
			default:
				return "未知";
		}
	};

	//编辑
	let [isModalOpenEdit, setIsModalOpenEdit] = useState(false);
	let [edit_data, set_edit_data] = useState<any>({});
	//------------socket 部分
	let [operation_item, set_operation_item] = useState<any>({});
	let member_length = useRef(0);
	let num = useRef(0);
	//运行 多个用户发送
	const operation = (item: any) => {
		set_operation_item(item);
		member_length.current = item.member.length;
		item.member.forEach((i: any) => {
			let params = JSON.stringify({
				action: "api/device/app/launch",
				payload: {
					sn: i.device_sn,
					app: item.scene_file_name,
				},
			});
			socket.send(params);
		});
	};
	let launch_arr = useRef([] as any);
	//运行接收
	addSocketNotify("api/device/app/launch", async (msg: any) => {
		if (msg.action != "api/device/app/launch") return;
		console.log(msg);

		num.current++;
		launch_arr.current.push({ message: msg.message, sn: msg.payload.sn });
		if (num.current == member_length.current) {
			try {
				await play_program_switch({ status: 1, program_id: operation_item.program_id, devices_sn_arr: launch_arr.current });
				launch_arr.current = [];
				num.current = 0;
				message.success("运行成功");
				set_is_list_data(!is_list_data);
			} catch (err) {
				launch_arr.current = [];
				num.current = 0;
			}
		}
	});

	//结束
	const close = async (item: any, status: number) => {
		set_operation_item(item);
		item.member.forEach((i: any) => {
			let params = JSON.stringify({
				action: "api/device/app/stop",
				payload: {
					sn: i.device_sn,
				},
			});
			socket.send(params);
		});
		await play_program_switch({ status, program_id: item.program_id });
		message.success("结束成功");
		set_is_list_data(!is_list_data);
	};

	//重启
	const restart = async (item: any) => {
		await close(item, 2);
		operation(item);
	};

	const items = [
		{
			key: "0",
			label: "全部",
		},
		{
			key: "1",
			label: "待运行",
		},
		{
			key: "2",
			label: "运行中",
		},
		{
			key: "3",
			label: "已结束",
		},
	];
	//tabs
	const onChange = (key: string) => {
		console.log(key);
		set_params({ ...params, status: Number(key) });
	};

	//tabs吸附窗口
	useEffect(() => {
		let control = document.querySelector("#control");
		let ant_tabs_nav = document.querySelector(".ant-tabs-nav");
		control?.addEventListener("scroll", function (e: any) {
			let top = e.target.scrollTop;
			if (top >= 200) {
				if (ant_tabs_nav?.getAttribute("id")) return;
				ant_tabs_nav?.setAttribute("id", "fixed");
			} else {
				ant_tabs_nav?.removeAttribute("id");
			}
		});
	}, []);

	//获取长链接状态
	let [websocket_status, set_websocket_status] = useState({} as any);
	let time = null as any;
	useEffect(() => {
		time = setInterval(() => {
			let obj = getWsStatus();
			set_websocket_status(obj);
			console.log(obj);
		}, 3000);

		return () => {
			clearInterval(time);
		};
	}, []);

	const websocket_status_fn = (status: number) => {
		switch (status) {
			case 1:
				return (
					<div className="c-#161940">
						<Badge status="success" /> 播控服务连接成功
					</div>
				);
			case 2:
				return (
					<div className="c-#161940">
						<Badge status="error" /> 播控服务连接失败
					</div>
				);
			default:
				break;
		}
	};

	return (
		<section>
			<Tabs
				defaultActiveKey="0"
				items={items}
				onChange={onChange}
				tabBarExtraContent={websocket_status_fn(websocket_status.status)}
			/>
			<section>
				<ul>
					{list_data.map((item: any, index: number) => (
						<li className="border-rd-10px p-24px pl-20px pr-20px mb-20px bg-#F7F8FF " key={index}>
							<div className="  flex justify-between">
								<div className="flex">
									<Image width={180} style={{ borderRadius: "5px" }} src={item.cover_url} />
									<div className="ml-20px font-700 flex flex-col justify-around">
										<div>
											<div className="flex">
												<h3 className="c-#161940">{item.scene_name}</h3>
												{item_status(item.status)}
											</div>

											<p className="c-#5C5F7A">{item.desc}</p>
										</div>

										<ul className="flex text-14px">
											<li className="flex mr-28px">
												<UserOutlined style={{ fontSize: "16px", color: "#9697A9" }} />
												<span className="c-#9697A9 ml-5px">成员</span>
												<span className="c-#161940 ml-5px">{item.tourist_num}人</span>
											</li>
											<li className="flex mr-28px">
												<DashboardOutlined style={{ fontSize: "16px", color: "#9697A9" }} />
												<span className="c-#9697A9 ml-5px">时长</span>
												<span className="c-#161940 ml-5px">{item.exp_duration}min</span>
											</li>
											{item.status == 2 && (
												<li className="flex mr-28px">
													<DashboardOutlined style={{ fontSize: "16px", color: "#9697A9" }} />
													<span className="c-#9697A9 ml-5px">预计剩余</span>
													<span className="c-#161940 ml-5px">10min32s</span>
												</li>
											)}
										</ul>
									</div>
								</div>
								<div className="flex items-center">
									{item.status != 2 && (
										<Popconfirm
											title="删除方案"
											description="是否确认删除此方案、删除后不可恢复"
											onConfirm={async () => {
												await del_studio_program({ program_id: item.program_id });
												set_is_list_data(!is_list_data);
												message.success("删除成功");
											}}
											okText="删除"
											cancelText="取消">
											<Button icon={<DeleteOutlined />} className="mr-10px w-110px">
												删除
											</Button>
										</Popconfirm>
									)}
									{item.status == 2 && (
										<div>
											<Button
												icon={<SyncOutlined />}
												className="ml-57px mr-10px bg-#5864FF c-#fff w-110px"
												onClick={() => restart(item)}>
												重新开始
											</Button>
											<Popconfirm
												title="结束"
												description="提前结束将不会保存当前进度"
												onConfirm={() => close(item, 3)}
												okText="确定"
												cancelText="取消">
												<Button danger className="w-110px">
													结束
												</Button>
											</Popconfirm>
										</div>
									)}
									{item.status == 1 && (
										<div>
											<Button
												icon={<RetweetOutlined />}
												className=" mr-10px w-110px"
												onClick={() => push("/scene_studio/scene_member_code?program_id=" + item.program_id)}>
												修改方案
											</Button>
											<Button
												className=" bg-#21AB68 c-#fff w-110px"
												icon={<CaretRightOutlined />}
												onClick={() => {
													operation(item);
												}}>
												运行
											</Button>
										</div>
									)}
								</div>
							</div>
							{/* 参与人 */}

							<ul className="flex gap-20px mt-24px overflow-x-auto memberUl" id="member">
								{item.member.map((i: any, index: number) => (
									<li
										className="flex flex-shrink-0 flex-col items-center bg-#fff border-rd-10px w-200px h-227px box-border p-20px relative"
										key={index}>
										<img src={i.avatar_url} alt="" className="w-44px h-44px border-rd-1/2" />

										<p className=" text-14px mt-10px mb-18px c-#161940">
											{i.char_name || "默认昵称"}{" "}
											{i.visualize_gender == "F" ? (
												<WomanOutlined style={{ color: "#F79999" }} />
											) : (
												<ManOutlined style={{ color: "#4E36FC" }} />
											)}
										</p>
										<div className="pico flex items-center gap-12px font-700 c-#21AB68">
											<i className="i2"></i>
											<i className="i3"></i>
											{i.battery}%
										</div>
										{i.device_sn && (
											<div className="flex pico items-center mt-14px">
												<i className="i1"></i>
												<p className="font-700 text-14px ml-10px">{i.device_name}</p>
											</div>
										)}

										{item.status == 2 && (
											<p className="absolute right-0 top--6px text-center mt-5px  custom_border bg-#EDEEFF text-12px c-#5864FF p-3px pl-8px pr-8px ">
												{i.launch_status}
											</p>
										)}
										{!i.ticket_no && <p className="c-#9697A9 text-12px mt-5px">未关联入场票</p>}
										{!i.device_sn && <p className="c-#9697A9 text-12px mt-5px">未关联设备</p>}
									</li>
								))}
							</ul>
						</li>
					))}
				</ul>
				<div className="flex justify-center mt-20px">
					<Pagination
						defaultCurrent={1}
						total={params.total}
						hideOnSinglePage={true}
						onChange={e => set_params({ ...params, page: e })}
					/>
				</div>
			</section>
			{isModalOpenEdit && <Add_edit type={"edit"} isModalOpen={[isModalOpenEdit, setIsModalOpenEdit]} edit_data={edit_data} />}
		</section>
	);
}
